package com.itheima.mongo;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.itheima.mongoservice.MovementServiceApi;
import com.itheima.pojo.mongo.Friend;
import com.itheima.pojo.mongo.Movement;
import com.itheima.pojo.mongo.MovementTimeLine;
import com.itheima.utils.IdWorker;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class MovementServiceApiImpl implements MovementServiceApi {
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public String pushMovement(Movement movement) {
        //自动生成策略封装pid
        movement.setPid(idWorker.getNextId("movement"));
        movement.setCreated(System.currentTimeMillis());
        //保存到movement集合中
        Movement save = mongoTemplate.save(movement);
        //异步处理
        saveMovementTimeLine(movement);
        //取出id并返回
        return Convert.toStr(save.getId());
    }

    @Override
    public List<Friend> getUserFriend(Long uid) {
        Query query = Query.query(Criteria.where("userId").is(uid));
        return mongoTemplate.find(query, Friend.class);
    }

    @Override
    public List<Movement> getMovements(Integer page, Integer pagesize, List<MovementTimeLine> movementTimeLine) {
        List<Movement> movements = new ArrayList<>();
        for (MovementTimeLine timeLine : movementTimeLine) {
            Query query = Query.query(Criteria.where("id").is(timeLine.getMovementId())
                            .and("state").is(1))
                    .with(Sort.by(Sort.Order.desc("created")));
            Movement movement = mongoTemplate.findOne(query, Movement.class);
            if (ObjectUtil.isNull(movement)){
                continue;
            }
            movements.add(movement);
        }
        return movements;
    }

    @Override
    public List<MovementTimeLine> getMovementTimeline(Integer page, Integer pagesize, Long uid) {
        //查询时间线动态
        Query queryAll = Query.query(Criteria.where("friendId").is(uid))
                .with(Sort.by(Sort.Order.desc("created")))
                .skip((page-1)*pagesize).limit(pagesize);
        return mongoTemplate.find(queryAll, MovementTimeLine.class);
          //筛选好友动态
//        List<Movement> friendMovements = new ArrayList<>();
//        for (Movement movement : allMovements) {
//            for (Friend friend : friends) {
//                if (Objects.equals(movement.getUserId(), friend.getFriendId())){
//                    friendMovements.add(movement);
//                }
//            }
//        }
    }

    @Override
    public Movement getMovementInfo(String id) {
        Query query = Query.query(Criteria.where("id").is(id));
        return mongoTemplate.findOne(query, Movement.class);
    }

    @Override
    public Movement getMovementInfoById(ObjectId movementId) {
        return mongoTemplate.findOne(Query.query(Criteria.where("id").is(movementId)), Movement.class);
    }

    @Override
    public void updateMovement(Movement movementInfo) {
        //查询对应动态
        Movement movement = mongoTemplate.findOne(Query.query(Criteria.where("id").is(movementInfo.getId())), Movement.class);
        if (ObjectUtil.isNull(movement)) {
            return;
        }
        //添加更新数据
        movement.setLikeCount(movementInfo.getLikeCount());
        movement.setLoveCount(movementInfo.getLoveCount());
        movement.setCommentCount(movementInfo.getCommentCount());
        //存回数据库
        mongoTemplate.save(movement);
    }

    @Override
    public List<Movement> getMovementsByUid(Integer page, Integer pagesize, Long uid, Integer state) {
        if (ObjectUtil.isNull(state)){
            if (ObjectUtil.isNull(uid)){
                Query query = new Query()
                        .skip((page-1)*pagesize).limit(pagesize);
                return mongoTemplate.find(query, Movement.class);
            }
            Query query = Query.query(Criteria.where("userId").is(uid))
                    .skip((page-1)*pagesize).limit(pagesize);
            return mongoTemplate.find(query, Movement.class);
        }else {
            if (ObjectUtil.isNull(uid)){
                Query query = new Query(Criteria.where("state").is(state))
                        .skip((page-1)*pagesize).limit(pagesize);
                return mongoTemplate.find(query, Movement.class);
            }
            Query query = Query.query(Criteria.where("userId").is(uid).and("state").is(state))
                    .skip((page-1)*pagesize).limit(pagesize);
            return mongoTemplate.find(query, Movement.class);
        }
    }

    @Override
    public Long getMovementCount(Integer state, Long uid) {
        if (ObjectUtil.isNull(state)){
            if (ObjectUtil.isNull(uid)) {
                return mongoTemplate.count(new Query(), Movement.class);
            }
            return mongoTemplate.count(Query.query(Criteria.where("userId").is(uid)), Movement.class);
        }
        Query query = Query.query(Criteria.where("state").is(state));
        return mongoTemplate.count(query, Movement.class);

    }

    @Override
    public void updateMovementState(Movement movement) {
        Movement one = mongoTemplate.findOne(new Query(Criteria.where("id").is(movement.getId())), Movement.class);
        if (ObjectUtil.isNotNull(one)){
            one.setState(movement.getState());
            mongoTemplate.save(one);
        }
    }

    @Override
    public List<Movement> getMovementsByPid(Integer page, Integer pagesize, Long pid) {
        Query query = Query.query(Criteria.where("pid").is(pid)).skip((page-1)*pagesize).limit(pagesize);
        return mongoTemplate.find(query, Movement.class);
    }

    @Override
    public List<Movement> randomMovement(Integer page, Integer pagesize) {
        TypedAggregation typedAggregation = Aggregation.newAggregation(Movement.class,
                Aggregation.sample(pagesize));
        AggregationResults<Movement> movements = mongoTemplate.aggregate(typedAggregation,Movement.class);
        return movements.getMappedResults();
    }

    @Override
    public List<Movement> getMyMovements(Integer page, Integer pagesize, Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Order.desc("created")))
                .skip((long) (page - 1)*pagesize).limit(pagesize);
        return mongoTemplate.find(query, Movement.class);
    }



    @Async
    public void saveMovementTimeLine(Movement movement){
        //对timeLine集合进行处理
        Query query = Query.query(Criteria.where("userId").is(movement.getUserId()));
        //查询朋友总数
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        for (Friend friend : friends) {
            MovementTimeLine movementTimeLine = new MovementTimeLine();
            movementTimeLine.setMovementId(movement.getId());
            movementTimeLine.setUserId(movement.getUserId());
            movementTimeLine.setCreated(movement.getCreated());
            movementTimeLine.setFriendId(friend.getFriendId());
            mongoTemplate.save(movementTimeLine);
        }
        //存登陆者与登陆者时间线信息
        MovementTimeLine movementTimeLine = new MovementTimeLine();
        movementTimeLine.setMovementId(movement.getId());
        movementTimeLine.setUserId(movement.getUserId());
        movementTimeLine.setCreated(movement.getCreated());
        movementTimeLine.setFriendId(movement.getUserId());
        mongoTemplate.save(movementTimeLine);
    }
}
